
import { _decorator, Component, Node ,EditBoxComponent ,LabelComponent ,find} from 'cc';
import {MgobeUtil} from "./mgobeUtil";
import {Constant} from "../framework/constant";
import {ClientEvent} from "../framework/clientEvent";
import {GameState, Player} from "./GameState";
import {DisplayManager} from "./displayManager";
import i18n from "../i18nMaster/runtime-scripts/LanguageData";
const { ccclass, property } = _decorator;

/**
 * Predefined variables
 * Name = InitGame
 * DateTime = Fri Dec 17 2021 18:25:16 GMT+0800 (中国标准时间)
 * Author = yly1234560
 * FileBasename = initGame.ts
 * FileBasenameNoExtension = initGame
 * URL = db://assets/scripts/core/initGame.ts
 * ManualUrl = https://docs.cocos.com/creator/3.3/manual/zh/
 *
 */
const COUNT_DOWN_TIME: number = 3;
@ccclass('InitGame')
export class InitGame extends Component {

    @property([LabelComponent])
    public aryPlayerName: LabelComponent[] = [];
    @property([LabelComponent])
    public aryPlayerstatus: LabelComponent[] = [];

    // [2]
    @property(Node)
    public ndReady: Node = null!;

    @property(Node)
    public ndInit: Node = null!;

    @property(Node)
    public ndJoin: Node = null!;

    @property(EditBoxComponent)
    public openIdEditBox: EditBoxComponent = null!;

    @property(EditBoxComponent)
    public roomIdEditBox: EditBoxComponent = null!;

    @property(LabelComponent)
    public lbTips: LabelComponent = null!;


    private _parent: DisplayManager = null!;
    private _isReady: boolean = false;
    private _countDownTime: number = 0;
    private _roomId: string = '';
    private _isGuide: boolean = false;//是否已经展示过引导了
    private _debugClickTimes: number = 0;//调试点击次数

    start () {
        this.openIdEditBox.node.active = true;
        this.ndInit.active = true;
        this.roomIdEditBox.node.active = false;
        this.ndJoin.active = false;

        let node = find("Canvas/display") as Node;
        this._parent = node.getComponent(DisplayManager);
    }

    onEnable () {
        ClientEvent.on(Constant.EVENT_NAME.ON_GET_ROOM_ID, this._onGetRoomId, this);
    }

    onDisable () {
        ClientEvent.off(Constant.EVENT_NAME.ON_GET_ROOM_ID, this._onGetRoomId, this);
    }


    public initSDK(){
        if (!this.openIdEditBox.string) return;
        MgobeUtil.instance.initSDK(this.openIdEditBox.string, '', '', () => {
            this.ndJoin.active = true;
            this.roomIdEditBox.node.active = true;
        });
    }

    public onJoinBtnClick() {
        // this.ndJoin.active = false;
        MgobeUtil.instance.joinRoom(this.roomIdEditBox.string);
    }

    public _onGetRoomId(roomId: string, readyState: boolean){
        if (!roomId) {
            console.error("###房间号错误", roomId);
            return;
        }

        this._roomId = roomId;
        this.roomIdEditBox.string = roomId;
        // this.ndReady.active = !readyState;
        this._updatePlayerState();


        // 所有包含window暂理解为微信时使用
        //@ts-ignore
        // window.roomId = roomId;
    }

    private _updatePlayerState() {
        let gameState: GameState = this._parent.logicManager.currentGameState;
        let players: Array<Player> = gameState.players;

        for (let idx = 0; idx < players.length; idx++) {
            // let lbTips: LabelComponent = this.aryNodeTips[idx].getComponent(LabelComponent) as LabelComponent;
            let player: Player = players[idx];
            if (!player.channel) {
                this._showPlayerReady(idx, false);
                continue;
            }

            if (player.channel.openId) {
                this.aryPlayerName[idx].string = player.channel.name;
            }

            switch(player.channel.state) {
                case Constant.CUSTOM_PLAYER_STATUS.CONNECTED:
                    this.aryPlayerstatus[idx].string = i18n.t("ready.waitPrepare");
                    break;
                case Constant.CUSTOM_PLAYER_STATUS.UNCONNECTED:
                    this.aryPlayerstatus[idx].string = i18n.t("ready.waitConnect");
                    break;
                case Constant.CUSTOM_PLAYER_STATUS.READY:
                    this.aryPlayerstatus[idx].string = i18n.t("ready.readyBtn");
                    break
            }
        }
        this._checkStart();
    }

    // public playerReady(){
    //     MgobeUtil.instance.changeCustomPlayerStatus(3);
    // }
    public onReadyBtnClick() {
        // this.ndReady.active = false;
        MgobeUtil.instance.changeCustomPlayerStatus(Constant.CUSTOM_PLAYER_STATUS.READY);
    }

    private _checkStart(){
        let players: Array<Player> = this._parent.logicManager.currentGameState.players;
        let result: Array<Player> = players.filter((value: Player) => {
            return value.channel && value.channel.state === Constant.CUSTOM_PLAYER_STATUS.READY;
        });


        if (result.length >= Constant.MIN_PLAYER) {
            this._isReady = true;
            this._countDownTime = COUNT_DOWN_TIME;
        } else {
            this._isReady = false;
        }
    }

    update (deltaTime: number) {
        // Your update function goes here.
        if (this._isReady) {
            //正准备进入游戏
            if (this._countDownTime <= 0) {
                return;
            }

            this._countDownTime -= deltaTime;

            this.lbTips.string = i18n.t("ready.countdown%{value}", { value: Math.ceil(this._countDownTime).toString()});

            if (this._countDownTime <= 0) {
                //可以进入游戏了
                this._parent.gameStart();

            }
        }
    }

    private _showPlayerReady (idx: number, isReady: boolean) {
        // this.aryNodeTips[idx].active = !isReady;
        // this.aryNodeWait[idx].active = !isReady;
        // this.aryNodeCheck[idx].active = isReady;

        if(isReady){
            this.aryPlayerstatus[idx].string = "已连接";
        }else {
            this.aryPlayerstatus[idx].string = "等待连接";
        }
    }
}

/**
 * [1] Class member could be defined like this.
 * [2] Use `property` decorator if your want the member to be serializable.
 * [3] Your initialization goes here.
 * [4] Your update function goes here.
 *
 * Learn more about scripting: https://docs.cocos.com/creator/3.3/manual/zh/scripting/
 * Learn more about CCClass: https://docs.cocos.com/creator/3.3/manual/zh/scripting/ccclass.html
 * Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.3/manual/zh/scripting/life-cycle-callbacks.html
 */
